package com.hui.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hui.admin.common.enums.ErrorCodeEnum;
import com.hui.admin.common.exception.UserException;
import com.hui.admin.dto.request.BookPageRequestDTO;
import com.hui.admin.dto.response.BookPageResponseDTO;
import com.hui.admin.entity.BookDO;
import com.hui.admin.mapper.BookMapper;
import com.hui.admin.service.BookService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 图书服务实现
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, BookDO> implements BookService {
    @Override
    public BookPageResponseDTO getBookPageList(BookPageRequestDTO requestDTO) {

        Page<BookDO> page = new Page<>(requestDTO.getPageNum(), requestDTO.getPageSize());

        // 构造查询条件
        LambdaQueryWrapper<BookDO> queryWrapper = new LambdaQueryWrapper<>();

        if (StrUtil.isNotBlank(requestDTO.getName())) {
            queryWrapper.like(BookDO::getName, requestDTO.getName());
        }

        if (StrUtil.isNotBlank(requestDTO.getAuthor())) {
            queryWrapper.like(BookDO::getAuthor, requestDTO.getAuthor());
        }

        Page<BookDO> bookList = baseMapper.selectPage(page, queryWrapper);

        List<BookDO> list = bookList.getRecords();

        BookPageResponseDTO result = new BookPageResponseDTO();

        result.setList(list);
        result.setTotal(bookList.getTotal());

        return result;
    }

    @Override
    public void createBook(BookDO bookDO) {
        if (bookDO == null) {
            throw new UserException(ErrorCodeEnum.BOOK_ADD_FAILED);
        }
        boolean flag = save(bookDO);
        if (!flag) {
            throw new UserException(ErrorCodeEnum.BOOK_ADD_FAILED);
        }
    }

    @Override
    public void updateBook(BookDO bookDO) {
        if (bookDO == null) {
            throw new UserException(ErrorCodeEnum.BOOK_ADD_FAILED);
        }
        boolean flag = updateById(bookDO);
        if (!flag) {
            throw new UserException(ErrorCodeEnum.BOOK_ADD_FAILED);
        }
    }

    @Override
    public void deleteBook(Long id) {
        if (id == null) {
            throw new UserException(ErrorCodeEnum.BOOK_NOT_EXISTS);
        }
        boolean flag = removeById(id);
        if (!flag) {
            throw new UserException(ErrorCodeEnum.BOOK_NOT_EXISTS);
        }
    }

    @Override
    public void deleteBooks(Long[] ids) {
        if (ids == null || ids.length == 0) {
            throw new UserException(ErrorCodeEnum.BOOK_NOT_EXISTS);
        }
        boolean flag = removeByIds(Arrays.asList(ids));
        if (!flag) {
            throw new UserException(ErrorCodeEnum.BOOK_NOT_EXISTS);
        }
    }
}